package com.sanhuo.triild.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author zzs
 * @version 1.0
 * @describe 数据库连接信息
 * @createTime 2018.1.5
 */
public class ConnectionUtil {

    private static Connection connection = null;

    private ConnectionUtil() {

    }

    /**
     * 根据配置文件 获取数据库连接
     *
     * @return Connection
     */
    public static Connection getConncetion() {
        Map<String, String> config = getJDBCConfig();

        try {
            Class.forName(config.get("driverClass"));
            connection = (Connection) DriverManager.getConnection(
                    config.get("url"), config.get("username"),
                    config.get("password"));

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 获取JDBC配置文件信息
     *
     * @return map
     */
    private static Map<String, String> getJDBCConfig() {
        Map<String, String> config = new HashMap<String, String>();

        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(
                    ConnectionUtil.class.
                            getClassLoader().
                            getResource("TriildConfig.xml"));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //如果 assert [boolean]  boolean 为true，则程序继续执行。
        //如果为false，则程序抛出AssertionError，并终止执行。
        assert document != null;
        //获取根元素
        Element root = document.getRootElement();
        for (Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            config.put(element.attributeValue("name"), element.getText());
        }

        return config;
    }
}
